<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2023/5/4
 * Time: 13:54
 * Desc: 管理员
 */
declare (strict_types=1);

namespace app\backend\controller;

use app\backend\base\controller\Base;
use app\backend\validate\AdminValidate;

class Admin extends Base
{
    /**
     * 列表
     */
    public function index()
    {
        if (request()->isPost()) {
            $validate = new AdminValidate();
            $ret = $validate->scene('index')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $page = input('page/d', 1);
            $limit = input('limit/d', 20);
            $fieldName = input('field_name', '');
            $fieldValue = input('field_value', '');
            $roleId = input('role_id/d', 0);

            //条件
            $where = [];

            //字段筛选
            if (!empty($fieldName) && !empty($fieldValue)) {
                switch ($fieldName) {
                    case 'account'://账号
                        $where[] = ['account', '=', $fieldValue];
                        break;
                    case 'nickname'://昵称
                        $where[] = ['nickname', 'like', "%{$fieldValue}%"];
                        break;
                }
            }

            //角色ID
            if (!empty($roleId)) {
                $where[] = ['role_id', '=', $roleId];
            }

            $list = [];
            $count = \app\extend\model\Admin::where($where)->count();
            if ($count > 0) {
                $list = \app\extend\model\Admin::where($where)->append(['role_name_txt'])->page($page)->limit($limit)->select();
            }
            return json([
                'code' => 0,
                'msg' => '获取成功',
                'count' => $count,
                'data' => $list,
            ])->send();
        } else {
            $roleList = \app\extend\model\Role::field('id,role_name')->select();
            return view('index', [
                'role_list' => $roleList
            ]);
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if (request()->isPost()) {
            $validate = new AdminValidate();
            $ret = $validate->scene('add')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $account = input('account', '');
            $nickname = input('nickname', '');
            $roleId = input('role_id/d', 0);

            $adminInfo = \app\extend\model\Admin::where([
                ['account','=',$account]
            ])->field('id')->find();
            if(!empty($adminInfo)){
                return json(_E('账号已存在'));
            }

            $result = \app\extend\model\Admin::insert([
                'account' => $account,
                'nickname' => $nickname,
                'role_id' => $roleId,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            if (!$result) {
                return json(_E('添加失败'));
            } else {
                return json(_S('添加成功'));
            }
        }
    }

    /**
     * 修改
     */
    public function edit()
    {
        if (request()->isPost()) {
            $validate = new AdminValidate();
            $ret = $validate->scene('edit')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id/d', 0);
            $account = input('account', '');
            $nickname = input('nickname', '');
            $roleId = input('role_id/d', 0);

            $adminInfo = \app\extend\model\Admin::where([
                ['account','=',$account],
                ['id','<>',$id]
            ])->field('id')->find();
            if(!empty($adminInfo)){
                return json(_E('账号已存在'));
            }

            $result = \app\extend\model\Admin::where([
                ['id', '=', $id]
            ])->update([
                'account' => $account,
                'nickname' => $nickname,
                'role_id' => $roleId,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            if (!$result) {
                return json(_E('修改失败'));
            } else {
                return json(_S('修改成功'));
            }
        }
    }

    /**
     * 删除
     */
    public function del()
    {
        if (request()->isPost()) {
            $validate = new AdminValidate();
            $ret = $validate->scene('del')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id/d', 0);

            $result = \app\extend\model\Admin::where([
                ['id', '=', $id]
            ])->delete();
            if (!$result) {
                return json(_E('删除失败'));
            } else {
                return json(_S('删除成功'));
            }
        }
    }

    /**
     * 修改状态
     */
    public function editStatus()
    {
        if (request()->isPost()) {
            $validate = new AdminValidate();
            $ret = $validate->scene('editStatus')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id/d', 0);
            $status = input('status/d', 0);

            $result = \app\extend\model\Admin::where([
                ['id', '=', $id]
            ])->update([
                'status' => $status,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            if (!$result) {
                return json(_E('修改状态失败'));
            } else {
                return json(_S('修改状态成功'));
            }
        }
    }

    /**
     * 修改密码
     */
    public function editPassword()
    {
        if (request()->isPost()) {
            $validate = new AdminValidate();
            $ret = $validate->scene('editPassword')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $oldPsw = input('oldPsw','');
            $newPsw = input('newPsw', '');

            $adminInfo = \app\extend\model\Admin::where([
                ['id','=',session('uid')]
            ])->field('id,password,salt')->find();

            //判断旧密码是否正确
            if($adminInfo->password != md5(md5($oldPsw).$adminInfo->salt)){
                return json(_E('旧密码错误'));
            }

            $pwdArr = password($newPsw);

            $result = \app\extend\model\Admin::where([
                ['id', '=', session('uid')]
            ])->update([
                'password' => $pwdArr['password'],
                'salt' => $pwdArr['salt'],
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            if (!$result) {
                return json(_E('修改密码失败'));
            } else {
                return json(_S('修改密码成功'));
            }
        } else {
            return view('edit_password');
        }
    }

    /**
     * 重置密码
     */
    public function resetPassword()
    {
        if (request()->isPost()) {
            $validate = new AdminValidate();
            $ret = $validate->scene('resetPassword')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $id = input('id/d',0);
            $password = input('password', '');

            $pwdArr = password($password);

            $result = \app\extend\model\Admin::where([
                ['id', '=', $id]
            ])->update([
                'password' => $pwdArr['password'],
                'salt' => $pwdArr['salt'],
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            if (!$result) {
                return json(_E('重置密码失败'));
            } else {
                return json(_S('重置密码成功'));
            }
        }
    }
}
